package com.cdwm.mrp.common.config.security;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cdwm.mrp.common.constant.CommonConstants;
import com.cdwm.mrp.common.tools.ResultCode;
import com.cdwm.mrp.common.tools.ResultVO;
import com.cdwm.mrp.domain.po.User;
import com.cdwm.mrp.mapper.UserMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.PrintWriter;


/**
 * @version v1.0
 * @Author: lyw
 * @Date: 2021/8/3
 */
@EnableWebSecurity
@Slf4j
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("userServicesImpl")
    private UserDetailsService detailsService;

    @Autowired
    private UserMapper userMapper;


    /**
     * 忽略的路径
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
       web.ignoring().antMatchers(CommonConstants.IGNORED_STATIC_RESOURCES.split(","));
    }


    /**
     * 请求授权
     * @param http
     * @throws Exception
     */
   @Override
    protected void configure(HttpSecurity http) throws Exception {
       http.csrf()
               .disable()
               .formLogin()
               .loginPage("/toLogin")
               .usernameParameter("username")
               .passwordParameter("password")
               .loginProcessingUrl("/loginMethod")
               .successHandler((request,response,authentication)->{
                   log.info(" authentication.getName():{}", authentication.getName());

                   QueryWrapper<User> queryWrapper = new QueryWrapper<>();

                   queryWrapper.lambda().eq(User::getUsername,authentication.getName());

                   User user = userMapper.selectOne(queryWrapper);

                   log.info("Session中的用户: {}",user);

                   request.getSession().setAttribute("user",user);

                   response.setContentType("application/json;charset=utf-8");
                   PrintWriter out = response.getWriter();
                   out.write(new ObjectMapper().writeValueAsString(ResultVO.ok()));
                   out.flush();
                   out.close();
               })
               .failureHandler((request,response,authentication)->{
                   response.setContentType("application/json;charset=utf-8");
                   PrintWriter out = response.getWriter();
                   out.write(new ObjectMapper().writeValueAsString(ResultVO.fail()));
                   out.flush();
                   out.close();
               })
               .and().rememberMe().rememberMeParameter("remember");
        //需要认证的请求
        http.authorizeRequests()
                .antMatchers(CommonConstants.REQUEST_RESOURCES_PERMIT_ALL.split(","))
                .permitAll()
                .anyRequest().authenticated();

        // 防止iframe 造成跨域
        http.headers().frameOptions().disable();

    }



    /**
     * 请求认证
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(detailsService).passwordEncoder(bCryptPasswordEncoder());

    }

    /**
     * 使用Spring默认的加密算法
     * @return
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){

        return new BCryptPasswordEncoder();
    }
}
